# _*_ coding:UTF-8 _*_
"""
__author__ = 'shede333'
"""

import os
import shutil
import time
import random


def file_name_add_date(file_name, name_suffix=None):
    """
    在文件名后面增加：日期后缀+其他后缀
    :param file_name: 原始文件名
    :param name_suffix: (可选)文件名后缀（放在date的后面）
    :return: 修改后的的文件名
    """
    time_format = "%Y%m%d%H%M%S"
    time_str = time.strftime(time_format, time.localtime())
    name_component = list(os.path.splitext(file_name))
    if name_suffix is not None:
        name_component.insert(1, name_suffix)
    name_component.insert(1, time_str)
    new_name = ''.join(name_component)
    return new_name


def check_log(log_file_path, backup_dir_path, max_size_mb=10):
    """
    检查log文件大小，超出限制后迁移到备份目录内
    :param log_file_path: log文件路径
    :param backup_dir_path:
    :param max_size_mb:
    :return:
    """
    if not os.path.exists(log_file_path):
        return
    file_size_mb = os.path.getsize(log_file_path) * 1.0 / (1024.0 * 1024)
    if file_size_mb < max_size_mb:
        return
    # 开始迁移备份文件:
    if not os.path.exists(backup_dir_path):
        os.makedirs(backup_dir_path)
    tmp_file_name = log_file_path.split("/")[-1]
    new_name = file_name_add_date(tmp_file_name)
    new_path = os.path.join(backup_dir_path, new_name)
    if os.path.exists(new_path):
        tmp_suffix = "_" + str(random.randint(1, 100000))
        new_name = file_name_add_date(tmp_file_name, name_suffix=tmp_suffix)
        new_path = os.path.join(backup_dir_path, new_name)
    shutil.move(log_file_path, new_path)
